<?php
namespace Home\Controller;

class AjaxActionController extends HomeController{
    function delCollect(){
      
        $type=I('request.type');
        $id=I('request.id');
        
        if($type=='product'){
            !is_login() && $this->error('请先登录',U('user/collectProduct'));
            $M_collect = M('collect_product');            
            $result = $M_collect->where(array(
                    'id' => $id
            ))->delete();
            
            $result ?  $this->ajaxReturn(array('status'=>1)) : $this->error('删除失败',U('user/collectProduct'));
        }else if($type=='shop'){
            !is_login() && $this->error('请先登录',U('user/collectShop'));
            $M_collect = M('collect_shop');
            $result = $M_collect->where(array(
                    'id' => $id
            ))->delete();            
            $result ?  $this->ajaxReturn(array('status'=>1)) : $this->error('删除失败',U('user/collectShop'));
        }
        
    }
    
    function delbrowse(){
        !is_login() && $this->error('请先登录',U('user/marks'));
        $id=I('request.id');       
        $M_collect = M('collect_browse');
        $result = $M_collect->where(array(
                'id' => $id
        ))->delete();        
        $result ?  $this->ajaxReturn(array('status'=>1)) : $this->error('删除失败',U('user/marks'));
    }
    
        
    /**
     * 设为默认地址
     */
    public function receiveDefault(){
        !is_login() && $this->error('请先登录',U('user/receives'));
        $M_member_receive=M('member_receive');
        $id=I('request.id');         
        $map=array('id'=>$id,'uid'=>UID);
         
        !$M_member_receive->where($map)->find() && $this->error('地址不存在',U('recives'));
         
        $M_member_receive->where(array('uid'=>UID))->setfield('is_default',0);
    
        $M_member_receive->where($map)->setfield('is_default',1) ? $this->ajaxReturn(array('status'=>1))  : $this->error('设置失败');
    }
    
    public function saveOrder(){
        if(IS_POST){
            $cartid=I('post.cartid');
            $receive_id=I('post.receive_id');
            if(empty($cartid) && empty(I('post.productid')))
            {
                $this->error('没有选中商品',U('order/carts'));
            }
        
            $M_cart=M('cart');
            $M_order=M('order');
            $M_product=M('product');
            $M_order_product=M("order_product");
            $M_receive=M('member_receive');
        
            $receive_info=$M_receive->find($receive_id);
            $order_data=array();
            $order_data['address']=$receive_info['address'];
            $order_data['consignee']=$receive_info['realname'];
            $order_data['mobile']=$receive_info['mobile'];
            $order_data['province_id']=$receive_info['province_id'];
            $order_data['city_id']=$receive_info['city_id'];
            $order_data['area_id']=$receive_info['area_id'];
            $order_data['create_time']=NOW_TIME;
            $order_data['update_time']=NOW_TIME;
            $order_data['status']=0; /*未付款*/
            $order_data['uid']=UID;
        
            $shopdata=array();
            //区分处理cart或直接处理产品
            //优先处理购物车
            if($cartid){
                is_array($cartid) && $cartid=implode(',', $cartid);        
                $carts=$M_cart->where(array('id'=>array('in',$cartid)))->field('product_id,quantity,price,total_price')->select();
                 
                //删除购物车
               // $M_cart->where(array('id'=>array('in',$cartid)))->setfield('status',0);
                 
                /*---店铺分组数据---*/
                foreach($carts as &$item){
                    $cartinfo=$M_cart->find($item['id']);
                    $tem_product=$M_product->field('uid,shop_id,title,price,category_id')->find($item['product_id']);
                    $item['product_title']=$tem_product['title'];
                    $item['shop_id']=$tem_product['shop_id'];
                    $item['identify_price']=  get_table_field($tem_product['category_id'],'product_category_id','price','identify') | 0;
                    $item['create_time']=NOW_TIME;
                    $item['update_time']=NOW_TIME;
                    $item['option_ids']=0;
                    $item['unit_price']=$item['price'];
                    $item['price']=$item['total_price'];
                    $item['product_attr']='默认';
                    if($tem_product['shop_id']){
                        $shopdata[$tem_product['shop_id']][]=$item;
                    }
                    else{
                      //  array_push($shopdata,$item);
                        $shopdata[][]=$item;
                    }
                }
                /*---店铺分组数据---*/
            }
            //直接将产品转化为订单
            else{
                $productid=I('post.productid');
                $quantity=I('post.quantity');
                $product_data=array();
                $tem_product=$M_product->field('uid,shop_id,title,price,category_id')->find($productid);
                $product_data['quantity']=$quantity;
                $product_data['price']=(double)$tem_product['price']*$quantity;
                $product_data['unit_price']=(double)$tem_product['price'];
                $product_data['product_id']=$productid;
                $product_data['product_title']=$tem_product['title'];
                $product_data['shop_id']=$tem_product['shop_id'];
                $product_data['identify_price']=  get_table_field($tem_product['category_id'],'product_category_id','price','identify') | 0;
                $product_data['create_time']=NOW_TIME;
                $product_data['update_time']=NOW_TIME;
                $product_data['option_ids']=0;
                $product_data['product_attr']='默认';
                $shopdata[$productid][]=$product_data;
            }             
        
            //全部商品总价
            $total=0;
            $now_order_id=array();
            $now_order_no=array();
             
            foreach($shopdata as $shop_array){
                //订单总价
                $total_price=0;
                //统计订单总价
                
                if(is_array($shop_array)){
                    for($i=0;$i<count($shop_array);$i++){
                        $total_price += $shop_array[$i]['price'];
                    }
                }else{
                    $total_price+=(int)$shop_array['price'];                   
                }               
              
                $total +=$total_price;
               
                //生成订单号
                $order_data['order_no']=build_no();
                $order_data['price']=$total_price;
              
                $order_id=$M_order->add($order_data);
                empty($order_id) && $this->error('出现故障');
                if($order_id){
                    $now_order_id[]=$order_id;
                    $now_order_no[]=$order_data['order_no'];
                    //订单商品
                    foreach($shop_array as &$product_item){
                        $product_item['order_id']=$order_id;
                       
                        $M_order_product->add($product_item);
                    }
                    addMessage(2,'订单通知','您的订单'.$order_data['order_no'].'已经确认,请及时付款',UID);
                }
            }
            empty($now_order_id) && $this->error('下单失败');
            $param=array();
            $param['order_id']=implode(',', $now_order_id);
            $param['order_no']=implode(',', $now_order_no);          
            $this->success('下单成功,即将跳转到支付页面',U('order/pay',$param));
        }else{
            $this->error('非post提交,操作非法');
        }
    }
    
    /**
     * 评论
     */
    public function goodscomment(){
        !is_login() && $this->error('请先登录',U('user/orders'));
        
        $orderid=I('orderid');
        $produdtid=I('productid');
        $content=I('content');
        $rating_desc=I('rating_desc');
        $rating_attitude=I('rating_attitude');
        $rating_speed=I('rating_speed');
        $rating_shipping=I('rating_shipping');
        
        
        $rate=I('rate');  
        $cover_id=I('cover_id');        
        is_array($cover_id) && $cover_id=implode(',', $cover_id);
       

        $M_product_comment=M('product_comment');
        $M_order=M("order");
        $M_order_product=M('order_product');
        
        $order_info=$M_order->find($orderid);
        
        empty($order_info) && $this->error('不存在的订单 ',U('user/orders'));
        $result=0;
        for($i=0;$i<count($produdtid);$i++){
            $data=array();
            $data['content']=$content[$i];
            $data['product_id']=$produdtid[$i];
            $data['order_id']=$orderid;
            $data['rating_desc']=$rating_desc[$i];
            $data['rating_attitude']=$rating_attitude[$i];
            $data['rating_speed']=$rating_speed[$i];
            $data['rating_shipping']=$rating_shipping[$i];
            $data['cover_ids']=$cover_id;
            $data['create_time']=NOW_TIME;
            $data['uid']=UID;
            $data['rate']=$rate[$i];
            
            $result=$M_product_comment->add($data);
            if(empty($result)){
                break;
            } 
        }        
       
        //更新订单状态
        if($result){
        $M_order->where(array('id'=>$data['order_id']))->setfield('status',7);
        $M_order_product->where(array('order_id'=>$data['order_id'],
            'product_id'=>$data['product_id']))->setfield('is_comment',1);
        }
        $result ? $this->success('成功',U('user/orders')) : $this->error('评论失败');
      
    }
    
    /**
     *退货申请
     *@param int type 退款类型
     *@param int order_id 订单id
     *@param int product_id 退款产品
     *@param double money 退款金额
     *@param stirng reason
     *@param string explain 退款说明
     */
    public function applyforReturn(){
        !is_login() && $this->error('请先登录',U('user/orderCancel'));
        $M_order=M('order');
        $M_order_produdt=M('order_product');
        $M_product_return=M('product_return');
         
        $type=I('type');
        $order_id=I('orderid');
        $money=I('money');
        $reason=I('reason');
        $explain=I('explain');
        //type 1 退款 2退货
        $cover_ids=I('post.cover_ids');
        is_array($cover_ids) && $cover_ids=implode(',', $cover_ids);
        empty($reason) && $this->error('请选择退款原因');
        empty($money) && $this->error('请选择确定退款金额');
        
        $data=array();
        $data['order_id']=$order_id;
        $data['money']=$money;
        $data['reason']=$reason;
        $data['explain']=$explain;
        $data['cover_ids']=$cover_ids;
        $data['type']=$type;
    
        //订单信息
        $order_info=$M_order->where(array('id'=>$order_id,'uid'=>UID))->find();
        empty($order_info) && $this->error('订单不存在');
       
         
        //退款条件
        if((int)$order_info['status']<=0 ||  (int)$order_info['status']>6 ){
            $this->error('此订单不符合退款条件');
        }
    
        !preg_match("/^1|2$/",$data['type']) && $this->error('退款方式错误');
        !preg_match("/^[0-9]+(.[0-9]{2})?$/",$data['money']) && $this->error('退金额错误格式错误');
        !preg_match("/^.{0,200}$/",$data['reason']) && $this->error('退款原因200字以内');
        !preg_match("/^.{0,250}$/",$data['explain']) && $this->error('退说明250字以内');
        if((int)$type==2){
            empty($product_id) && $this->error('请选择退款商品');
        }
        $data['create_time']=NOW_TIME;
        $data['uid']=UID;
        $data['status']=1;        
         
        //检查退货表
        $M_product_return->where(array('status'=>2,'product_id'=>$data['product_id'],
            'order_id'=>$data['order_id']))->find() && $this->error('退款已完成');
         
        $M_product_return->where(array('status'=>1,'product_id'=>$data['product_id'],
            'order_id'=>$data['order_id']))->find() && $this->error('退款申请已提交,请等待商家退款');
         
    
        //检查订单表是否已经退货
        $map_order_product=array('product_id'=>$data['product_id'],
            'order_id'=>$data['order_id']);
        $map_order_product['return_status']=array('BETWEEN',"1,2");
         
        $M_order_produdt->where($map_order_product)->find() && $this->error('退款申请冲突，请联系管理员');
         
        $apply_result=$M_product_return->add($data);
         
        if($apply_result){
            $M_order_produdt
            ->where(array('product_id'=>$data['product_id'],'order_id'=>$data['order_id']))
            ->setfield('return_status',1);
            $M_order->where(array('id'=>$data['order_id']))->setfield('status',6);
        }
         
        $apply_result   ? $this->success('成功申请退款',U('user/orders')): $this->error('申退失败');
    }
    
    /**
     * 关闭订单
     */
    public function closeOrder(){
        !is_login() && $this->error('请先登录',U('user/orders'));
        $id=I('orderid');
        $M_order=M('order');
       
        $map=array('id'=>$id,'uid'=>UID);
        empty($M_order->where($map)->find()) && $this->error('订单不存在');
        
        $M_order->where($map)->save(array('status'=>8,'update_time'=>NOW_TIME)) 
            ? $this->ajaxReturn(array('status'=>11))
        : $this->error('取消失败,请稍后再试'); 
    }
    /**
     * 上架 下架
     */
    public function putway(){
        !is_login() && $this->error('请先登录',U('user/xianzhi'));
        
        $id=I('id');
        $status=I('status');
        
        empty($id) && $this->error('闲置商品不存在');
        $status==='' && $this->error('请确定上架/下架');
        
        $M_product=M('product');
        $map=array('id'=>$id,'uid'=>UID);
        
        !preg_match('/^1|0$/', $status) && $this->error('参数值错误');
        $M_product->where($map) ->save(array('status'=>$status,'upate_time'=>NOW_TIME)) !==false
        ? $this->ajaxReturn(array('status'=>11)) : $this->error('操作失败');
        
    }
    
    /**
     * 删除商品
     */
    public function myproductdel(){
        !is_login() && $this->error('请先登录',U('user/xianzhi'));
        
        $id=I('id');
        $status=I('status');
        
        empty($id) && $this->error('闲置商品不存在');     
        
        $M_product=M('product');
        $map=array('id'=>$id,'uid'=>UID);
        
        $M_product->where($map) ->save(array('is_show'=>0,'upate_time'=>NOW_TIME)) !==false        
        ? $this->ajaxReturn(array('status'=>11)) : $this->error('操作失败');
    }
    
    /**
     * 订单收货
     */
    public function confirmGoods(){
        !is_login() && $this->error('请先登录',U('user/Orders'));
        $id=I('request.orderid');        
        $M_order=M('order');
        
        $orderinfo=$M_order->find($id);
        empty( $orderinfo) && $this->error('订单不存在');       
        $map=array('id'=>$id,'uid'=>UID);  
        
        $result=$M_order->where($map)->setfield('status',5); 
        
        if($result) {
            addMessage(2,'收货通知','您的订单号是'.$orderinfo['order_no'].'已确认收货',UID);
            $this->success('确认收货成功',U('User/orderComment',array('orderid'=>$id)));
        }else{
         $this->error('确认收货失败,请稍后再试');
        }
    }

    /**
     * 鉴定发货
     */
    public function checkupShip(){
        $checkup_id=I('checkupid');
        $shipping_code=I('shipping_code');
        $cover_id=I('cover_id');
        $code=I('code');
        is_array($cover_id) && $cover_id=implode(',',$cover_id);
        
        $M_checkup=M('checkup');
        $M_checkup_shipping=M('checkup_shipping');
        $data=array();
        $data['shipping_code']=$shipping_code;
        $data['checkup_id']=$checkup_id;
        $data['type']='seller';
        $data['code']=$code;
        $data['create_time']=NOW_TIME;
        $data['cover_ids']=$cover_id;
        
        $result=$M_checkup_shipping->add($data);
        if($result){
            $result =$M_checkup->where(array('id'=>$checkup_id))->save(array('status'=>2,'update_time'=>NOW_TIME));
        }
        $result ? $this->success('发货成功',U('identify/index')) : $this->error('发货失败');
    }
    
    /**
     * 删除鉴定
     */
    public function delCheckup(){
        
        !is_login() && $this->error('请先登录',U('user/login'));
        $checkup_id=I('checkupid');
        
        $M_checkup=M('checkup');
        $map=array('id'=>$checkup_id,'uid'=>UID);
        
        $M_checkup->where($map) ->save(array('is_show'=>0,'upate_time'=>NOW_TIME)) !==false
        ? $this->ajaxReturn(array('status'=>11)) : $this->error('操作失败');
    }
    
    /**
     * 鉴定收货
     * 
     */
    public function checkupConfirm(){
        !is_login() && $this->error('请先登录',U('user/login'));
        
        $checkupid=I('checkupid');
        $M_checkup=M('checkup');
        
        $M_checkup->where(array('id'=>$checkupid))->save(array('modify_time'=>NOW_TIME,'status'=>5)) ?
        $this->ajaxReturn(array('status'=>11,'url'=>U('Identify/index'))) : $this->error('确定收货失败');
    }
}
?>